var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var wxAuthFail = true;
// pages/order-confirm/order-confirm.js
var payType = 1; //1:立即支付; 2:提后付款
var isTest = false;
var progressNum = 0; //定义一个初始值0
var jindutiaoShow = false;
var quedingShow = false;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tc: 1,
    util: util,

    userinfo: {},
    cuid: 0,
    token: '',
    openid: '',

    choosenum: 0,

    wx_address: '',
    address: {},
    ps_address: {},
    zt_address: {},

    goodsinfoArr: [],
    kucun: 0,
    oneprice: 0,

    totalPrice: 0,
    yunfei: 0,

    my_cion: 68, //满 免运费
    set_yunfei: 5, // 运费

    user_jifen: 0,
    use_jf: 0,
    add_jf: 0,

    liuyan: '',

    textarea_w: 300,

    hour: 8,

    hasZitiAddr: false, //是否有自提地址
    ziti: false, //是否自提

    colorSet: '',

    jindutiaoTest: '正在派单中,请稍候',

    myhao: '',
    payTypeArray: [{
        id: 1,
        title: '线上支付'
      },
      {
        id: 2,
        title: '货到付款'
      }
    ],

    canInputJifen: false
  },

  user_jifen: 0,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
      jindutiaoTest: tc == 1 ? '正在派單中,請稍候' : '正在派单中,请稍候',
      choosenum: (options.choosenum ? options.choosenum : 1)
    });
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", this.data.choosenum);
    var titlename = tc == 1 ? '確認訂單' : '确认订单';
    wx.setNavigationBarTitle({
      title: titlename,
    })
    // var result = that.data.tc == 1 ? '購買成功' : '购买成功';
    // that.jindutiao(result);
    payType = options.payType == "2" ? 2 : 1;
    wx.showLoading({
      title: 'loading...',
      mask: 'true'
    })
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          textarea_w: res.windowWidth - 32,
          tc: tc
        })
      },
    })
    //获取颜色配置
    app.getColorSetData(function(color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });

    //获取关于等信息
    app.getAllAbout('contact', function(res) {
      that.setData({
        contact_phone: res
      })
    });


    //读取运费设置信息 
    this.getYunfeiSet();

    this.getLoginInfo();

    that.getgonghuoshang(1);


    //可控制每天的可下单时间段
    var date = new Date();
    var hour = date.getHours();

    var g_infoArr = JSON.parse(options.goodsArr);
    console.log("商品信息：", g_infoArr);
    var canInput = false;
    for (var i = 0; i < g_infoArr.length; i++) {
      if (g_infoArr[i].selltype == '1' || g_infoArr[i].selltype == '2') {
        canInput = true;
      }
    }
    this.setData({
      goodsinfoArr: g_infoArr,
      hour: hour,
      canInputJifen: canInput
    })

    //获取自提地址
    this.getZitiAddr();

  },

  getgonghuoshang: function(cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghs",
      orgid: util.orgid,
      page: cpage,
      num: 10
    }
    util.api({
      data: params,
      success: function(responseData) {
        var result = responseData.data;
        console.log("供货商数据：", result);
        var picker_arr = ["请选择"],
          id_arr = ["0"];
        for (var i = 0; i < result.length; i++) {
          if (result[i].gcataid == '189' || result[i].gcataid == '237' || result[i].gcataid == '412') {
            var uid = result[i].uid;
            var title = result[i].username;


            picker_arr.push(title);
            id_arr.push(uid);
          }
        }
        that.setData({
          picker_arr: picker_arr,
          id_arr: id_arr,
          postuid: id_arr[1]
        });

      }
    });
  },

  getLoginInfo: function() {
    var that = this;
    app.LoginUserInfo(function(res) {
      console.log("mine login:", res);
      wxAuthFail = res == -1; //用户拒绝授权
      if (wxAuthFail) {
        return;
      }
      that.setData({
        cuid: res.uid,
        openid: res.wxsmall_openid,
        token: res.token
      });
      that.getJifen(); //获取积分
      if (util.orgid != '12545' && util.orgid != '13078' && util.orgid != '19619') {
        that.getAddress(); //获取地址
      }
      that.getgonghuoshang(1);
    });
  },

  //重新读取 登录用户信息
  reGetUserInfo: function(e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },

  //获取自提地址
  getZitiAddr: function() {
    var that = this;
    //自提点地址
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "getpeisong",
        uid: util.orgid
      },
      success: function(responseData) {
        var data = responseData.data;
        console.log("自提地址：", data);
        if (data && data.length > 0) {
          that.setData({
            hasZitiAddr: true
          });
        }
        wx.hideLoading();
        if ((util.orgid == '13078' || util.orgid == '19619') && that.data.ziti == true) {
          that.setData({
            address: that.data.zt_address
          })
          console.log('that.data.zt_address：', that.data.zt_address);

        }
      }
    });
  },

  getJifen: function() {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getusersource",
        "uid": that.data.cuid
      },
      success: function(responseData) {
        console.log("积分", responseData.data)
        that.setData({
          user_jifen: responseData.data.source
        })
      }
    });
  },
  jifenInput: function(e) {
    var valueStr = e.detail.value;
    var valueNum = 0;
    if (valueStr) {
      valueNum = parseInt(valueStr);
      var userAllScore = parseInt(this.data.user_jifen);
      if (valueNum > userAllScore) {
        valueNum = userAllScore;
      }
      this.setData({
        use_jf: valueNum
      });
      this.user_jifen = valueNum;
    } else {
      this.user_jifen = 0;
    }
    this.calTotalPrice();
  },
  jifenInputBlur: function(e) {
    this.setData({
      use_jf: this.user_jifen
    });
  },

  radioChange: function(e) {
    var that = this;
    console.log('radio发生change事件，携带value值为：', e.detail.value);
    if (e.detail.value == 'zt') {
      this.setData({
        ziti: true,
        address: that.data.zt_address
      })
      console.log('that.data.zt_address：', that.data.zt_address);
    } else {
      this.setData({
        ziti: false,
        address: that.data.ps_address
      })
      console.log('that.data.ps_address：', that.data.ps_address);
    }
    this.calTotalPrice();
  },

  getAddress: function() {

    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getaddress",
        "uid": that.data.cuid
      },
      success: function(responseData) {
        var dataType = typeof responseData.data;
        console.log("收货地址：" + dataType, responseData)
        
        if (dataType == 'object' && responseData.data.length > 0) {
          for (var i = 1; i < responseData.data.length; i++) {
            var addrItem = responseData.data[i];
            that.delAddress(addrItem.id);
          }
          that.setData({
            address: responseData.data[0],
            ps_address: responseData.data[0]
          });
        } else {
          //读取微信收货地址
          if (util.orgid != '16708' && util.orgid != '13078' && util.orgid != '19619') {
            that.getWxAddress();

          }
        }
      }
    });
  },

  inputNameBlur: function(e) {
    console.log("名字= " + e.detail.value);
    var addr = this.data.address;
    addr.name = e.detail.value;
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        ps_address: addr
      })

    } else {
      this.setData({
        address: addr,
        zt_address: addr
      })
    }
  },

  inputPhoneBlur: function(e) {
    console.log("联系电话= " + e.detail.value);
    var addr = this.data.address;
    addr.phone = e.detail.value;
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        // zt_address: addr
      })

    }
  },

  inputAddressBlur: function(e) {
    console.log("地址= " + e.detail.value);
    var addr = this.data.address;
    addr.address = e.detail.value;
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        // zt_address: addr
      })

    }
  },

  setPSAddress: function(psd_addr) {
    var addr = this.data.address;
    addr.psd_phone = psd_addr.phone;
    addr.address = psd_addr.address + '-' + psd_addr.name;
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        ps_address: addr
      })

    } else {
      this.setData({
        address: addr,
        zt_address: addr
      })
    }
  },

  //减少动作
  reduceAction: function(e) {
    var index = e.currentTarget.dataset.itemid;
    var allGwcData = this.data.goodsinfoArr;
    var newInputValue = allGwcData[index].buycount - 1
    if (newInputValue < 1) {
      return;
    }
    allGwcData[index].buycount = newInputValue;
    this.setData({
      goodsinfoArr: allGwcData
    })
    this.calTotalPrice();
  },
  //增加动作
  addAction: function(e) {
    var index = e.currentTarget.dataset.itemid;
    var allGwcData = this.data.goodsinfoArr;
    var newInputValue = allGwcData[index].buycount + 1
    if (newInputValue > allGwcData[index].kucun) {
      wx.showToast({
        title: this.data.tc == 1 ? '超出庫存啦' : '超出库存啦',
      });
      newInputValue = allGwcData[index].kucun;
    }
    allGwcData[index].buycount = newInputValue;
    this.setData({
      goodsinfoArr: allGwcData
    })
    this.calTotalPrice();
  },

  //处理总价
  calTotalPrice: function() {
    var allData = this.data.goodsinfoArr;
    console.log("allData===", allData);
    var allGoodPrice = 0;
    var cangetJifen = 0; // 本次购买能得到的积分
    var canUseJifen = 0; // 可以使用的最大积分数
    for (var i = 0; i < allData.length; i++) {
      if (allData[i].sel) {
        if (allData[i].attribute) {
          var attribute = allData[i].attribute;
          for (var j = 0; j < attribute.length; j++) {
            if (attribute[j].attributePrice) {
              allGoodPrice += parseInt(attribute[j].attributePrice) * 100;
            }
          }
        }
        allGoodPrice += allData[i].price * allData[i].buycount;
        // Yunfei += parseInt(allData[i].yunfei) * 100;
        cangetJifen += allData[i].source * allData[i].buycount;
        if (allData[i].selltype == '1' || allData[i].selltype == '2') {
          canUseJifen += parseInt(allData[i].sellscore);
        }
      }
    }

    var yunfei = this.data.set_yunfei;
    if (allGoodPrice / 100 >= this.data.my_cion) {
      yunfei = 0;
    }
    allGoodPrice += (yunfei * 100);
    //积分抵扣
    console.log("canUseJifen == " + canUseJifen);
    if (this.user_jifen > 0) {
      if (this.user_jifen > canUseJifen) {
        this.setData({
          use_jf: canUseJifen
        });
        this.user_jifen = canUseJifen
      }
      allGoodPrice -= this.user_jifen;
    }

    if (!this.data.ziti) {
      var allPrice = (allGoodPrice / 100.0).toFixed(2);
    }
    if ((this.data.ziti)) {
      var allPrice = (allGoodPrice / 100.0).toFixed(2) - yunfei;
    }
    this.setData({
      totalPrice: allPrice,
      yunfei: yunfei,
      add_jf: cangetJifen
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  liuyanInput: function(e) {
    console.log("留言：" + e.detail.value);
    this.setData({
      liuyan: e.detail.value
    });
  },

  confirmOrder: function() {
    var that = this;
    
      if (util.orgid == '18681' && that.data.totalPrice < 20) {
        wx.showModal({
          title: '提示',
          content: '20元起送',
          confirmText: "去凑单",
          success: function(res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.navigateTo({
                url: '/pages/goodslist/goodslist?uid=18697&gcataid=566&username=澳卡鲜奶',
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      } else {
        that.payTypeSelect();

      }
    
  },

  payTypeSelect: function() {
    this.paygoodsAction();
  },

  //确认订单动作
  paygoodsAction: function() {
    this.paygoodsCard();
  },

  //非着数皇
  paygoodsCard: function() {
    if (util.orgid != '15938' && util.orgid != '16708' && util.orgid != '12545' && wxAuthFail && util.orgid != '19619') {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.cuid + 'wxsmallpaycarts' + that.data.token);
    var tc = app.get_tc();
    if (!that.data.address.name && this.data.choosenum == 1) {
      app.dialog(tc == 1 ? '請添加收貨人姓名' : '请添加收货人姓名', 'loading');
      return;
    }
    if (!that.data.address.phone && this.data.choosenum == 1) {
      app.dialog(tc == 1 ? '請添加聯系電話' : '请添加联系电话', 'loading');
      return;
    }
    if (!that.data.address.address && this.data.choosenum == 1) {
      app.dialog(tc == 1 ? '請添加收貨地址' : '请添加收货地址', 'loading');
      return;
    }

    // that.saveAddress();
    var cartinfoArr = [];
    var pin = 0;
    for (var i = 0; i < this.data.goodsinfoArr.length; i++) {
      var goodsItem = this.data.goodsinfoArr[i];
      var g_info = {};
      g_info.goods_id = goodsItem.id;
      g_info.goods_name = goodsItem.title;
      g_info.guige = goodsItem.selGuige ? goodsItem.selGuige.id : '';
      g_info.count = goodsItem.buycount;
      g_info.yunfei = goodsItem.yunfei;
      // g_info.coin = goodsItem.price * goodsItem.buycount + g_info.yunfei * 100;
      g_info.coin = goodsItem.price * goodsItem.buycount;
      g_info.linkcode = goodsItem.linkcode;
      cartinfoArr = cartinfoArr.concat(g_info);
      pin = (goodsItem.pin == 1 ? goodsItem.pinzong : 0);
    }
    var data = {
      'cartinfo': JSON.stringify(cartinfoArr),

      'uid': that.data.cuid,
      'type': 'goods',
      'total_fee': that.data.totalPrice,
      'allcoin': that.data.totalPrice * 100,
      'consignee': that.data.address.name,
      'phone': that.data.address.phone,
      'addr': that.data.address.address,
      'psd_phone': that.data.address.psd_phone ? that.data.address.psd_phone : '',
      'subject': that.data.tc == 1 ? '購買商品-批量結算' : '购买商品-批量结算',
      'openid': that.data.openid,
      'publickey': util.publiccode,
      'ac': "wxsmallpaycarts",
      'privatekey': privatekey,
      'del_source': that.user_jifen,
      'add_source': that.data.add_jf,
      'message': that.data.liuyan,
      'pin': pin,
      'ziti': that.data.ziti ? 1 : 0,
      'isdraw': payType == 2 ? 1 : 0,
      'booktime': wx.getStorageSync("booktime") || '现在就送',
    };
    console.log("购物车订单参数：", data);
    // return;
    //下单请求
    util.api({
      data: data,
      method: 'POST',
      success: function(responseData) {
        var data = responseData.data;

        console.log(data);
        that.setData({
          out_trade_no: data.out_trade_no
        })
        if (isTest) {
          that.paytuisong();
        }
        if (data.res === true) {
          if (payType == 2) {
            var result = that.data.tc == 1 ? '下單成功' : '下单成功';
            that.jindutiao(result);
            console.log("下單成功：before======clearGouwuche", data);
            if (util.orgid == 13078 || util.orgid == 19619) {
              that.zsh_clearGouwuche();

            } else {
              that.clearGouwuche();

            }
            // app.dialogToast('下单成功', 'success', function () {
            //   wx.redirectTo({
            //     url: '/pages/order-list/order-list',
            //   });
            // });
            // that.clearGouwuche();
          } else {
            if (that.data.totalPrice <= 0) {
              that.paySuccess();
            } else {
              //挂起微信支付请求
              var orderData = data.data;
              wx.requestPayment({
                'timeStamp': orderData.timeStamp,
                'nonceStr': orderData.nonceStr,
                'package': orderData.package,
                'signType': orderData.signType,
                'paySign': orderData.paySign,
                'success': function(res) {
                  that.paySuccess();
                },
                'fail': function(res) {
                  console.log(res);
                  if (res.errMsg == 'requestPayment:fail cancel') {

                  } else {
                    app.dialog(that.data.tc == 1 ? '購買失敗' : '购买失败', 'loading');
                  }
                }
              });
            }
          }

        } else {
          app.dialog(that.data.tc == 1 ? '購買失敗' : '购买失败', 'loading');
        }
      }
    });
  },

  //支付成功处理
  paySuccess: function() {
    var that = this;
    this.clearGouwuche();
    if (this.data.add_jf > 0) {
      var toice = that.data.tc == 1 ? '恭喜你獲得' : "恭喜你获得 " + this.data.add_jf + that.data.tc == 1 ? '積分' : " 积分";
      wx.showModal({
        title: that.data.tc == 1 ? '購買成功' : '购买成功',
        content: toice,
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            var result = that.data.tc == 1 ? '購買成功' : '购买成功';
            that.jindutiao(result);

            // wx.redirectTo({
            //   url: '/pages/order-list/order-list',
            // });
          }
        }
      })
    } else {
      var result = that.data.tc == 1 ? '購買成功' : '购买成功';
      that.jindutiao(result);
      // app.dialogToast('购买成功', 'success', function () {
      //   wx.redirectTo({
      //     url: '/pages/order-list/order-list',
      //   });
      // });
    }
  },

  clearGouwuche: function() {
    if (payType == 2) {
      var gwc_datas = wx.getStorageSync('draw_datas');
    } else {
      var gwc_datas = wx.getStorageSync('gwc_datas');
    }
    if (gwc_datas && gwc_datas.length > 0) {
      var new_gwc_datas = [];
      for (var i = 0; i < gwc_datas.length; i++) {
        var g_id = gwc_datas[i].id;
        var guige_id = gwc_datas[i].selGuige ? gwc_datas[i].selGuige.id : '';
        var notPay = true;
        for (var n = this.data.goodsinfoArr.length - 1; n >= 0; n--) {
          var pay_g_id = this.data.goodsinfoArr[n].id;
          var pay_guige_id = this.data.goodsinfoArr[n].selGuige ? this.data.goodsinfoArr[n].selGuige.id : '';
          if (g_id == pay_g_id && guige_id == pay_guige_id) {
            notPay = false;
            break;
          }
        }
        if (notPay) {
          new_gwc_datas = new_gwc_datas.concat(gwc_datas[i]);
        }
      }
      if (new_gwc_datas.length > 0) {
        if (payType == 2) {
          wx.setStorageSync('draw_datas', new_gwc_datas);
        } else {
          wx.setStorageSync('gwc_datas', new_gwc_datas);
        }

      } else {
        if (payType == 2) {
          wx.removeStorageSync("draw_datas");
        } else {
          wx.removeStorageSync("gwc_datas");
        }

      }
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // this.getAddress();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  goAtherPage: function(e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url
    })
  },

  getWxAddress: function() {
    var that = this;
    wx.chooseAddress({
      success: function(res) {
        // console.log("收货地址：")
        // console.log(res.userName)
        // console.log(res.postalCode)
        // console.log(res.provinceName)
        // console.log(res.cityName)
        // console.log(res.countyName)
        // console.log(res.detailInfo)
        // console.log(res.nationalCode)
        // console.log(res.telNumber)
        var addr = res.provinceName + res.cityName + res.countyName + res.detailInfo;
        that.setData({
          wx_address: res,
          address: {
            name: res.userName,
            phone: res.telNumber,
            address: addr
          }
        });
        that.saveAddress();
      },
      fail: function() {
        wx.showModal({
          title: '提示',
          content: that.data.tc == 1 ? '獲取通訊地址失敗，這將影響您的使用體驗，是否重新設置授權？' : '获取通讯地址失败，这将影响您的使用体验，是否重新设置授权？',
          showCancel: true,
          cancelText: "否",
          confirmText: "是",
          success: function(res) {
            if (res.confirm) {
              wx.OpenSetting({
                success: function(res) {
                  console.log(res);
                  console.log('success');
                  that.getWxAddress();
                },
                fail: function() {
                  console.log('fail');
                }
              })
            } else if (res.cancel) {
              console.log('用户点击否')
            }
          }
        })
      }
    })
  },

  saveAddress: function() {
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(that.data.cuid + "addaddress" + that.data.token);
    util.api({
      data: {
        "privatekey": tmpmd5,
        "ac": "addaddress",
        "uid": that.data.cuid,
        "name": that.data.address.name,
        "phone": that.data.address.phone,
        "address": that.data.address.address,
        "psd_phone": that.data.address.psd_phone ? that.data.address.psd_phone : '',
        "default": 1
      },
      method: "POST",
      success: function(responseData) {
        that.getAddress();
      }
    });
  },

  delAddress: function(addrId) {
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(that.data.cuid + "deladdress" + that.data.token);
    util.api({
      method: "POST",
      data: {
        "privatekey": tmpmd5,
        "ac": "deladdress",
        "uid": that.data.cuid,
        "id": addrId
      },

      success: function(responseData) {
        console.log("删除地址：", responseData);
      }
    });
  },

  //获取运费设置
  getYunfeiSet: function() {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "xsdyunfei",
        "binduid": util.orgid
      },
      success: function(responseData) {
        console.log("运费：", responseData);
        var data = responseData.data;
        if (data.res != false) {
          console.log("运费：==1==");
          that.setData({
            my_cion: parseInt(data.mianfei),
            set_yunfei: parseInt(data.yunfei)
          })
        }

        that.calTotalPrice();
      }
    });
  },


  jindutiao: function(result) {
    var that = this;
    that.paytuisong();
    that.setData({
      jindutiaoShow: true,
    })
    var timer = setInterval(function() {
      progressNum++;
      //当进度条为100时清除定时任务
      if (progressNum >= 100) {
        clearInterval(timer);
        that.setData({
          jindutiaoTest: result,
          quedingShow: true,
        })
      }

      //并且把当前的进度值设置到progress中

      that.setData({
        progress: progressNum
      })
    }, 50)
  },


  //点击确定
  queding: function(e) {
    var that = this;
    wx.redirectTo({
      url: '/pages/order-list/order-list',
    });
    progressNum = 0;
  },
  //支付订单推送
  paytuisong: function() {
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(that.data.cuid + "paytuisong" + that.data.token);
    var data = {
      "privatekey": tmpmd5,
      "ac": "paytuisong",
      "uid": that.data.cuid,
      // "cartinfo": JSON.stringify(cartinfoArr),
      "binduid": util.orgid,
      "total_fee": that.data.totalPrice,
      "name": that.data.address.name,
      "phone": that.data.address.phone,
      "address": that.data.address.address,
      'message': that.data.liuyan,

    };

    if (util.orgid == 18681) {
      var g_info = '';
      for (var i = 0; i < this.data.goodsinfoArr.length; i++) {
        var goodsItem = this.data.goodsinfoArr[i];
        g_info = g_info + goodsItem.title + '  ' + goodsItem.buycount + ' 瓶；' + '  ';
      }
      data = {
        "privatekey": tmpmd5,
        "ac": "paytuisong",
        "uid": that.data.cuid,
        // "cartinfo": JSON.stringify(cartinfoArr),
        "binduid": util.orgid,
        "total_fee": that.data.totalPrice,
        "name": that.data.address.name,
        "phone": that.data.address.phone,
        "address": that.data.address.address,
        'message': that.data.liuyan,
        'out_trade_no': that.data.out_trade_no,
        'booktime': wx.getStorageSync("booktime") || '现在就送',
        "btime": that.toDate(new Date().getTime() / 1000),
        'goods_list': g_info
      }
    }
    util.api({
      data: data,
      method: "POST",
      success: function(responseData) {
        console.log("paytuisong===", responseData);
      }
    });
  },
  //下单管理员推送
  xiadantuisong: function() {
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(that.data.cuid + "fanhuaxiadantuisong" + that.data.token);
    util.api({
      data: {
        "privatekey": tmpmd5,
        "ac": "fanhuaxiadantuisong",
        "uid": that.data.cuid,
        "binduid": util.orgid,
        "name": that.data.address.name,
        "phone": that.data.address.phone,
        "btime": that.toDate(new Date().getTime() / 1000),
      },
      method: "POST",
      success: function(responseData) {
        console.log("paytuisong===", responseData);
      }
    });
  },

  resetNavColor: function() {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  //时间戳转换时间  
  toDate: function(number) {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear() + '.';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    console.log(Y + M + D + "  " + H + ':' + m)
    return (Y + M + D + "  " + H + ':' + m)

  },

  
  attributeShow: function(e) {
    console.log('eeee', e.currentTarget.dataset.attr)
    if (!this.data.attributeShow) {
      this.setData({
        attributeShow: true,
        attribute: e.currentTarget.dataset.attr

      })
    } else {
      this.setData({
        attributeShow: false,
        attribute: e.currentTarget.dataset.attr
      })
    }
  },
  
  bindPayTypePickerChange: function(e) {
    var that = this;
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      payTypeIndex: e.detail.value
    })
    payType = that.data.payTypeArray[e.detail.value].id;
  },
})